package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.dto.OrderPageQueryDto;
import com.itheima.common.dto.OrderUpdateDto;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @className OrderServiceImpl
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final MemberMapper memberMapper;

    /**
     * 分页查询预约信息
     * @param queryPageBean 分页条件
     * @return PageResult
     **/
    public PageResult getOrderByPage(QueryPageBean queryPageBean) {
        // 开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        // 查询预约列表
        List<Order> orderList = orderMapper.selectOrderByPage(queryPageBean.getQueryString());
        // 收集所有memberId
        List<Integer> memberIds = orderList.stream()
                .map(Order::getMemberId)
                .collect(Collectors.toList());
        // 批量查询Member
        Map<Integer, Member> memberMap = memberMapper.selectMembersByIds(memberIds)
                .stream()
                .collect(Collectors.toMap(Member::getId, Function.identity()));
        // 转换为DTO
        List<OrderPageQueryDto> orderPageQueryDtoList = orderList.stream()
                .map(order -> {
                    Member member = memberMap.get(order.getMemberId());
                    if (member == null) return null;
                    return OrderPageQueryDto.builder()
                            .name(member.getName())
                            .phoneNumber(member.getPhoneNumber())
                            .fileNumber(member.getFileNumber())
                            .orderType(order.getOrderType())
                            .orderStatus(order.getOrderStatus())
                            .orderDate(order.getOrderDate())
                            .build();
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return new PageResult(new PageInfo<>(orderPageQueryDtoList));
    }

    /**
     * 修改预约状态
     * @param orderUpdateDto 预约状态
     **/
    public void editOrderStatus(OrderUpdateDto orderUpdateDto) {
        orderMapper.updateOrderStatus(orderUpdateDto);
    }

}
